package com.boat.framework.common.thread.context;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.NamedThreadLocal;

import lombok.extern.slf4j.Slf4j;

/**
 * Mock上下文，用于保留从h5前端传入的请求头参数
 * 
 * @author 周江
 *
 */
@Slf4j
public class MockContext {
	private static final String KEY_HTTP_HEADER = "httpHeader";
	private static final ThreadLocal<Map<String, String>> HTTP_HEADER = new NamedThreadLocal<>("http请求头信息");

	public static void setHeader(Map<String, String> header) {
		HTTP_HEADER.set(header);
	}

	public static Map<String, String> getHeader() {
		return HTTP_HEADER.get();
	}

	public static boolean isEmptyOfContext() {
		return HTTP_HEADER.get() == null ? true : false;
	}

	public static void clear() {
		if (log.isDebugEnabled()) {
			log.debug("清理MockContext:{}", HTTP_HEADER.get());
		}
		HTTP_HEADER.remove();
	}

	// ------复制和恢复上下文
	public static Map<String, Object> getCopyOfContextMap() {
		Map<String, Object> contextMap = new HashMap<>(4);
		contextMap.put(KEY_HTTP_HEADER, getHeader());
		return contextMap;
	}

	public static void setContextMap(Map<String, Object> contextMap) {
		if (contextMap.get(KEY_HTTP_HEADER) != null) {
			setHeader((Map<String, String>) contextMap.get(KEY_HTTP_HEADER));
		}
	}

}
